﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NetFrameworkExtensions
{
  public class Restorer<T> : IDisposable
  {
    Action<T> setValue;
    T oldValue;
    T value;

    public Restorer(T oldValue, T newValue, Action<T> setValue)
    {
      if (setValue == null) throw new ArgumentNullException("setValue");

      this.value = newValue;
      this.setValue = setValue;
      this.oldValue = oldValue;
      setValue(newValue);
    }

    public void Dispose()
    {
      if (setValue != null)
      {
        setValue(oldValue);
        setValue = null;
      }
    }
  }

  public static class RestorerHelper
  {
    public static IDisposable SetWithRestore<T>(this T value, T newValue, Action<T> setValueFunc)
    {
      return new Restorer<T>(value, newValue, setValueFunc);
    }
  }
}
